package com.example.demo.service.impl;


import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.common.Result;
import com.example.demo.common.TokenUtils;
import com.example.demo.entity.Admin;
import com.example.demo.entity.dto.LoginDTO;
import com.example.demo.mapper.AdminMapper;
import com.example.demo.service.IAdminService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AdminService extends ServiceImpl<AdminMapper, Admin> implements IAdminService {
    @Autowired
    private AdminMapper adminMapper;
    private static final String DEFAULT_PASS = "123";
    public static final String PASS_SALT = "qingge";

    @Override
    public Result login(Admin admin) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", admin.getUsername());
        Admin admin1 = adminMapper.selectOne(queryWrapper);
        if (admin1 == null) {
            return Result.error("用户名不存在");
        }
        // 判断密码是否合法
        String securePass = securePass(admin.getPassword());
        if (!securePass.equals(admin1.getPassword())) {
            return Result.error("用户名或密码错误");        }
        if (!admin1.isStatus()) {
            return Result.error("当前用户处于禁用状态，请联系管理员");
        }
        LoginDTO loginDto = new LoginDTO();
        BeanUtils.copyProperties(admin1, loginDto);
        // 生成token
        String token = TokenUtils.genToken(String.valueOf(admin1.getId()), admin1.getPassword(),"admin");
        loginDto.setToken(token);
        return Result.success(loginDto);
    }

    @Override
    public Result changePass(Admin admin) {
        // 注意 你要对新的密码进行加密
        admin.setPassword(securePass(admin.getNewPass()));
        int count = adminMapper.updateById(admin);
        if (count <= 0) {
            return Result.error("修改密码失败");
        }
        return Result.success("修改密码成功");
    }

    private String securePass(String password) {
        return SecureUtil.md5(password + PASS_SALT);
    }

    public Result add(Admin admin) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", admin.getUsername());
        Admin admin1 = adminMapper.selectOne(queryWrapper);
        if (admin1 != null) {
            return Result.error("该账号已存在");
        }
        admin.setStatus(true);
        admin.setPassword(securePass(admin.getPassword()));
        int count = adminMapper.insert(admin);
        if (count <= 0) {
            return Result.error("添加管理员失败");
        }
        return Result.success("添加管理员成功");
    }

    public Result logout() {
        //清除token
        TokenUtils.clearToken();
        return Result.success("退出成功");
    }
}
